<template>
    <div class="contact">
        <div class="search">
            <el-input placeholder="搜索" prefix-icon="el-icon-search" v-model="search" size="small"> </el-input>
            <div class="plus" @click="showMessage">
                <i class="el-icon-plus" style="font-size: 14px"></i>
            </div>
        </div>
        <el-dialog
            title="创建群聊"
            width="640px"
            :visible.sync="formVisible"
            :close-on-click-modal="false"
            append-to-body
        >
            <div style="display: flex; margin-top: -20px; height: 345px">
                <div style="flex: 1; padding-right: 15px">
                    <el-input placeholder="搜索" v-model="filterText" prefix-icon="el-icon-search" size="small">
                    </el-input>
                    <el-tree
                        ref="tree"
                        :data="treeData"
                        :props="defaultProps"
                        show-checkbox
                        highlight-current
                        :default-expanded-keys="['100']"
                        node-key="code"
                        :filter-node-method="filterNode"
                        style="margin-top: 10px; height: 360px; overflow: auto"
                        @check="nodeCheck"
                    >
                        <span
                            slot-scope="{ node, data }"
                            style="display: flex; justify-content: center; align-items: center"
                        >
                            <i
                                class="el-icon-user"
                                v-if="data.type === 'user'"
                                style="font-size: 16px; margin-right: 6px; color: #3975c6"
                            ></i>
                            <i
                                class="el-icon-folder"
                                v-else
                                style="font-size: 16px; margin-right: 6px; color: #3975c6"
                            ></i>
                            <span>{{ node.label }}</span>
                        </span>
                    </el-tree>
                </div>
                <div style="flex: 1; overflow: auto">
                    <div
                        v-for="(item, index) in checkedUsers"
                        style="display: flex; align-items: center; margin-bottom: 10px"
                    >
                        <el-avatar
                            shape="square"
                            :src="item.avatar"
                            @error="true"
                            style="border-radius: 6px; width: 36px; height: 36px; line-height: 36px"
                        >
                            <div style="background: #007fff; font-size: 12px">
                                {{ item.name | obtainAlias }}
                            </div>
                        </el-avatar>
                        <span style="margin-left: 10px; width: 240px; color: #000">{{ item.name }}</span>
                        <i class="el-icon-close" @click="handleDelete(index, item.id)"></i>
                    </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="formVisible = false">取消</el-button>
                <el-button type="primary" @click="handleCreate">创建</el-button>
            </div>
        </el-dialog>
        <el-scrollbar style="height: 595px; scrollbar-width: none">
            <div v-for="(item, index) in filterTableData" :key="index" @click="handleClick(index)">
                <context-menu
                    class="chat"
                    :style="{
                        height: '62px',
                        background: index === selectedIndex ? '#D1DEF0' : '',
                        margin: '0px 5px',
                        'border-radius': '4px',
                        'border-bottom': '1px solid #E0E1E2'
                    }"
                    :menu="[{ label: '删除聊天' }]"
                    @select="handleMenu($event, index)"
                >
                    <div class="avatar">
                        <el-badge :value="item.unread" :max="99" :hidden="item.unread == 0">
                            <el-avatar
                                shape="square"
                                :src="item.avatar"
                                @error="true"
                                style="border-radius: 6px; width: 42px; height: 42px"
                                v-if="item.classify == 1"
                            >
                                <div style="background: #007fff; font-size: 12px; width: 42px; height: 42px">
                                    {{ item.name | obtainAlias }}
                                </div>
                            </el-avatar>
                            <el-avatar
                                shape="square"
                                :src="item.avatar"
                                @error="true"
                                style="border-radius: 6px; background: transparent; width: 42px; height: 42px"
                                v-else-if="item.classify == 2"
                            >
                                <img src="@/assets/group.png" style="width: 42px; height: 42px" />
                            </el-avatar>
                            <el-avatar
                                shape="square"
                                :src="item.avatar"
                                @error="true"
                                style="border-radius: 6px; background: transparent; width: 42px; height: 42px"
                                v-else-if="item.classify == 3"
                            >
                                <img src="@/assets/assistant.png" style="width: 42px; height: 42px" />
                            </el-avatar>
                        </el-badge>
                    </div>
                    <div style="width: 180px; display: flex; flex-direction: column; justify-content: center">
                        <div style="display: flex">
                            <div class="nickname">
                                {{ item.name }}
                            </div>
                            <div class="date">
                                {{ item.updateTime | formatDate }}
                            </div>
                        </div>
                        <div class="content emoji-font">
                            {{ item | formatContent }}
                        </div>
                    </div>
                </context-menu>
            </div>
        </el-scrollbar>
    </div>
</template>

<script>
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import calendar from 'dayjs/plugin/calendar'
dayjs.extend(calendar)
dayjs.locale('zh-cn')
export default {
    data() {
        return {
            search: '',
            tableData: [],
            selectedIndex: -1,
            formVisible: false,
            filterText: '',
            treeData: [],
            defaultProps: {
                label: 'name'
            },
            checkedUsers: []
        }
    },
    computed: {
        name() {
            return localStorage.getItem('name')
        },
        filterTableData() {
            return this.tableData.filter(key => {
                if (this.search != '') {
                    return key.name.indexOf(this.search) >= 0
                } else {
                    return true
                }
            })
        }
    },
    filters: {
        formatDate(value) {
            return dayjs(value).calendar(null, {
                sameDay: 'HH:mm',
                lastDay: '[昨天]',
                lastWeek: 'dddd',
                sameElse: 'YYYY/MM/DD'
            })
        },
        obtainAlias(value) {
            if (value.length <= 2) {
                return value
            } else {
                return value.substring(value.length - 2, value.length)
            }
        },
        formatContent(value) {
            if (value.type == 0) {
                return '撤回一条消息'
            } else if (value.type == 1) {
                return value.content
            } else if (value.type == 2) {
                return '[图片]'
            } else if (value.type == 3) {
                return '[文件] ' + JSON.parse(value.content).name
            } else if (value.type == 4) {
                return '[语音]'
            } else if (value.type == 5) {
                return '[视频]'
            }
            return value.content
        }
    },
    mounted() {
        this.queryContactList()
        this.queryAllUserData()
        this.$bus.$on('message', data => {
            let selectItem = this.tableData[this.selectedIndex]
            selectItem.type = data.type
            selectItem.content = data.content
            selectItem.msgid = data.msgid
            selectItem.updateTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
            this.tableData[this.selectedIndex] = selectItem
        })
        this.$bus.$on('receive', data => {
            let index = -1
            for (let i = 0; i < this.tableData.length; i++) {
                if (this.tableData.classify === 1) {
                    if (this.tableData[i].target === data.source) {
                        index = i
                        break
                    }
                } else {
                    if (this.tableData[i].sessionId === data.sessionId) {
                        index = i
                        break
                    }
                }
            }
            if (index === -1) {
                this.queryContactList()
            } else {
                if (this.selectedIndex === index) {
                    let selectItem = this.tableData[this.selectedIndex]
                    selectItem.type = data.type
                    selectItem.content = data.content
                    selectItem.updateTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
                    this.tableData[this.selectedIndex] = selectItem
                    this.$bus.$emit('receiveData', data)
                    this.cleanUnread(selectItem.id)
                } else {
                    let selectItem = this.tableData[index]
                    selectItem.type = data.type
                    selectItem.unread = selectItem.unread + 1
                    selectItem.content = data.content
                    selectItem.updateTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
                    this.tableData[index] = selectItem
                    this.$bus.$emit('update', this.tableData, -1)
                }
            }
        })
        this.$bus.$on('addMember', data => {
            for (let i = 0; i < this.tableData.length; i++) {
                let item = this.tableData[i]
                if (item.sessionId === data.sessionId) {
                    if (this.selectedIndex == i) {
                        this.$bus.$emit('update', this.tableData, this.selectedIndex)
                    }
                    break
                }
            }
        })
        this.$bus.$on('removeMember', data => {
            let source = data.source // 移动人员
            for (let i = 0; i < this.tableData.length; i++) {
                let item = this.tableData[i]
                if (item.sessionId === data.sessionId) {
                    if (source.includes(item.source)) {
                        this.tableData.splice(i, 1)
                        if (this.selectedIndex == i) {
                            this.$bus.$emit('update', this.tableData, -1)
                        }
                    } else {
                        if (this.selectedIndex == i) {
                            this.$bus.$emit('update', this.tableData, this.selectedIndex)
                        }
                    }
                    break
                }
            }
        })
        this.$bus.$on('modifyName', data => {
            for (let i = 0; i < this.tableData.length; i++) {
                let item = this.tableData[i]
                if (item.sessionId === data.sessionId) {
                    item.name = data.name
                    if (this.selectedIndex == i) {
                        this.$bus.$emit('update', this.tableData, this.selectedIndex)
                    }
                    break
                }
            }
        })
        this.$bus.$on('quit', data => {
            for (let i = 0; i < this.tableData.length; i++) {
                let item = this.tableData[i]
                if (item.sessionId === data.sessionId) {
                    if (item.source === data.source) {
                        this.tableData.splice(i, 1)
                        if (this.selectedIndex == i) {
                            this.$bus.$emit('update', this.tableData, -1)
                        }
                    } else {
                        if (this.selectedIndex == i) {
                            this.$bus.$emit('update', this.tableData, this.selectedIndex)
                        }
                    }
                    break
                }
            }
        })
        this.$bus.$on('revoke', data => {
            for (let i = 0; i < this.tableData.length; i++) {
                let item = this.tableData[i]
                if (item.msgid == data.msgid) {
                    item.type = 0
                    this.$set(this.tableData, i, item)
                    break
                }
            }
        })
    },
    beforeDestroy() {
        this.$bus.$off('message')
        this.$bus.$off('receive')
        this.$bus.$off('addMember')
        this.$bus.$off('removeMember')
        this.$bus.$off('modifyName')
        this.$bus.$off('quit')
        this.$bus.$off('revoke')
    },
    watch: {
        filterText(val) {
            this.$refs.tree.filter(val)
        }
    },
    methods: {
        filterNode(value, data) {
            if (!value) return true
            return data.name.indexOf(value) !== -1
        },
        async queryContactList() {
            let params = {
                name: this.search
            }
            let res = await this.$axios.post('contact/queryList', params)
            if (res.data.code == 200) {
                this.tableData = res.data.data
                this.$bus.$emit('update', this.tableData, -1)
            }
        },
        async queryAllUserData() {
            let res = await this.$axios.post('depart/queryAllUserData')
            if (res.data.code == 200) {
                this.treeData = res.data.data
            }
        },
        async cleanUnread(id) {
            let params = {
                id: id
            }
            let res = await this.$axios.post('contact/cleanUnread', params)
        },
        handleClick(index) {
            this.selectedIndex = index
            let selectItem = this.tableData[index]
            let unread = selectItem.unread
            selectItem.unread = 0
            this.tableData[index] = selectItem
            this.$bus.$emit('update', this.tableData, index)
            if (unread != 0) {
                this.cleanUnread(selectItem.id)
            }
        },
        async deleteLink(index) {
            let res = await this.$axios.post('contact/delete/' + this.tableData[index].id, {
                sessionId: this.tableData[index].sessionId
            })
            if (res.data.code == 200) {
                this.tableData.splice(index, 1)
                if (index == this.selectedIndex) {
                    this.selectedIndex = -1
                    this.$bus.$emit('update', this.tableData, -1)
                }
            }
        },
        handleMenu(option, index) {
            if (option.label === '删除聊天') {
                this.deleteLink(index)
            }
        },
        showMessage() {
            this.checkedUsers = []
            this.formVisible = true
            this.$nextTick(() => {
                this.$refs.tree.setCheckedNodes([])
            })
        },
        nodeCheck(data, { checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys }) {
            let checkedUsers = []
            for (let i = 0; i < checkedNodes.length; i++) {
                let node = checkedNodes[i]
                if (node.type === 'user') {
                    checkedUsers.push(node)
                }
            }
            this.checkedUsers = checkedUsers
        },
        handleDelete(index, id) {
            this.checkedUsers.splice(index, 1)
            this.$refs.tree.setChecked(id, false, false)
        },
        handleCreate() {
            let params = {
                name: this.name,
                data: JSON.stringify(this.checkedUsers)
            }
            if (this.checkedUsers.length === 0) {
                this.$message.error('请选中用户')
                return
            } else {
                this.$axios.post('contact/createChat', params).then(res => {
                    if (res.data.code == 200) {
                        if (this.checkedUsers.length > 1) {
                            this.tableData.unshift(res.data.data)
                            this.selectedIndex = 0
                            let selectItem = this.tableData[this.selectedIndex]
                            this.$bus.$emit('update', this.tableData, this.selectedIndex)
                        } else {
                            let index = -1
                            for (let i = 0; i < this.tableData.length; i++) {
                                if (this.tableData[i].id === res.data.data.id) {
                                    index = i
                                    break
                                }
                            }
                            if (index === -1) {
                                this.tableData.unshift(res.data.data)
                                this.selectedIndex = 0
                                let selectItem = this.tableData[this.selectedIndex]
                                this.$bus.$emit('update', this.tableData, this.selectedIndex)
                            } else {
                                this.selectedIndex = index
                                let selectItem = this.tableData[this.selectedIndex]
                                this.$bus.$emit('update', this.tableData, this.selectedIndex)
                            }
                        }
                        this.formVisible = false
                    } else {
                        this.$message.error(res.data.message)
                    }
                })
            }
        }
    }
}
</script>
<style scoped>
::v-deep .el-badge__content {
    height: 14px;
    line-height: 14px;
    padding: 0 4px;
}
.contact {
    width: 250px;
    background: #f0f0f1;
}
.search {
    padding: 15px 0px 15px 10px;
    display: flex;
    align-items: center;
}
.plus {
    width: 32px;
    text-align: center;
    background: #eee;
    margin: 0px 8px;
    border-radius: 4px;
    line-height: 26px;
    cursor: pointer;
    background: #e4e5e6;
}
.chat {
    display: flex;
    cursor: default;
}
.avatar {
    width: 56px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.nickname {
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    font-size: 14px;
}
.date {
    width: 60px;
    font-size: 10px;
    color: #a1a1a3;
    text-align: right;
}
.content {
    margin-top: 5px;
    color: #a1a1a3;
    font-size: 12px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    width: 160px;
}
::v-deep .el-scrollbar__wrap {
    overflow-x: hidden;
}
</style>
